package com.example.practice;


import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;


/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_2 extends Fragment implements View.OnClickListener {


    private TextView sort;
    private Integer[] integers = new Integer[4];
    private Spinner spinnerArrays;
    private Button query;
    private Button BCP;
    private TextView luk2;
    private TextView h2;
    private TextView lv2;
    private TextView ye2;
    private TextView cek2;
    private ListView list2;
    private List<CarUsers.DataBean> list = new ArrayList<>();

    public Fragment_2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_2, container, false);
        initView(view);
        spinner();
        retrofit();
        return view;
    }
    private interface Blogclient {
        @POST("setTrafficLightRGY")
        Call<ResponseBody> Blog(@Body RequestBody str);
    }
    private interface Blogsever {
        @GET("getTrafficLightRGY")
        Call<ResponseBody> Blog();
    }

    private void retrofit() {
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Blogsever blogsever = retrofit1.create(Blogsever.class);
        Call<ResponseBody> blog = blogsever.Blog();
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Gson gson = new Gson();
                    CarUsers carUsers = gson.fromJson(string, CarUsers.class);
                    List<CarUsers> listc = new ArrayList<>();
                    listc.add(carUsers);
                    list=listc.get(0).getData();
                    myAdapter myAdapter = new myAdapter(list);
                    list2.setAdapter(myAdapter);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    private class myAdapter extends BaseAdapter {
        List<CarUsers.DataBean> list = new ArrayList<>();
        public myAdapter(List<CarUsers.DataBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }
        private class ViewHolder{
            TextView luk;
            TextView red;
            TextView lvd;
            TextView yed;
            CheckBox checkBox1;
            Button button;
        }
        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if(view==null){
                view=LayoutInflater.from(getContext()).inflate(R.layout.table,null);
                holder=new ViewHolder();
                holder.luk = view.findViewById(R.id.lu);
                holder.red = view.findViewById(R.id.h);
                holder.lvd = view.findViewById(R.id.lv);
                holder.yed = view.findViewById(R.id.ye);
                holder.button=view.findViewById(R.id.button1);
                holder.checkBox1=view.findViewById(R.id.checkbox1);
                view.setTag(holder);
            }else {
                holder= (ViewHolder) view.getTag();
            }
            holder.luk.setText(list.get(i).getRoad()+"");
            holder.red.setText(list.get(i).getRed()+"");
            holder.lvd.setText(list.get(i).getGreen()+"");
            holder.yed.setText(list.get(i).getYellow()+"");
            holder.checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    integers[i] =list.get(i).getRoad();
                }
            });
            holder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                adigo(list.get(i).getRoad()+"");
                }
            });
            return view;
        }
    }
    private void adigo(final String i){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        final View longinDialogView= layoutInflater.inflate(R.layout.item_layout, null);//找到定义的布局
        builder.setView(longinDialogView);//设置布局
        final EditText redh = (EditText) longinDialogView.findViewById(R.id.redh);
        final EditText yeld = (EditText) longinDialogView.findViewById(R.id.yeld);
        final EditText gred = (EditText) longinDialogView.findViewById(R.id.gred);
        Button qr = (Button) longinDialogView.findViewById(R.id.qr);
        Button qx = (Button)longinDialogView.findViewById(R.id.qx);
        if(Integer.parseInt(i)!=0){
            redh.setHint(list.get(Integer.parseInt(i)).getRed()+"");
            yeld.setHint(list.get(Integer.parseInt(i)).getYellow()+"");
            gred.setHint(list.get(Integer.parseInt(i)).getGreen()+"");
        }
        builder.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
        final AlertDialog dialog = builder.create();  //创建对话框
        dialog.setCanceledOnTouchOutside(true); //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
        dialog.show();//展示Alert
        qr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str1, str2, str3;
                str1 = redh.getText().toString();
                str2 = yeld.getText().toString();
                str3 = gred.getText().toString();
                charge(i,str1, str2, str3);
                dialog.dismiss();
            }
        });
        qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }
    private void spinner() {
        final String[] arr = getResources().getStringArray(R.array.languages);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (getActivity(), android.R.layout.test_list_item, arr);
        spinnerArrays.setAdapter(adapter);
        spinnerArrays.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return dataBean.getRoad()-t1.getRoad();
                            }
                        });
                        break;
                    case 1:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return t1.getRoad()-dataBean.getRoad();
                            }
                        });
                        break;
                    case 2:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return dataBean.getRed()-t1.getRed();
                            }
                        });
                        break;
                    case 3:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return t1.getRed()-dataBean.getRed();
                            }
                        });
                        break;
                    case 4:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return dataBean.getYellow()-t1.getYellow();
                            }
                        });
                        break;
                    case 5:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return t1.getYellow()-dataBean.getYellow();
                            }
                        });
                        break;
                    case 6:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return dataBean.getGreen()-t1.getGreen();
                            }
                        });
                        break;
                    case 7:
                        Collections.sort(list, new Comparator<CarUsers.DataBean>() {
                            @Override
                            public int compare(CarUsers.DataBean dataBean, CarUsers.DataBean t1) {
                                return t1.getGreen()-dataBean.getGreen();
                            }
                        });
                        break;

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
    private void charge(String j,String str1,String str2,String str3){
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Blogclient blogsever = retrofit1.create(Blogclient.class);
        Map<String,Object> map = new HashMap<>();
        if(Integer.parseInt(j)==0){
            map.put("roadNum",integers);
        }else {
        map.put("roadNum",j+"");}
        map.put("red",str1);
        map.put("green",str2);
        map.put("yellow",str3);
        Gson gson = new Gson();
        String s = gson.toJson(map);
        Log.v("TAG","qwwqw"+s);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s);
        Call<ResponseBody> blog = blogsever.Blog(requestBody);
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Toast.makeText(getContext(), "充值成功", Toast.LENGTH_SHORT).show();
                retrofit();
        }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(getContext(), "充值失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void initView(View view) {
        sort = (TextView) view.findViewById(R.id.sort);
        spinnerArrays = (Spinner) view.findViewById(R.id.spinner_arrays);
        query = (Button) view.findViewById(R.id.query);
        query.setOnClickListener(this);
        BCP=view.findViewById(R.id.BCP);
        BCP.setOnClickListener(this);
        luk2 = (TextView) view.findViewById(R.id.luk2);
        h2 = (TextView) view.findViewById(R.id.h2);
        lv2 = (TextView) view.findViewById(R.id.lv2);
        ye2 = (TextView) view.findViewById(R.id.ye2);
        list2 = (ListView) view.findViewById(R.id.list2);
    }
    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.query:
                list2.setAdapter(new myAdapter(list));
                break;
            case R.id.BCP:
                adigo("0");
                break;
        }
    }
}